<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="BOM编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入BOM编码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="no">
              <a-input v-model="model.no" placeholder="请输入配方号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="BOM名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入BOM名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="BOM类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="category">
              <j-dict-select-tag
                type="list"
                v-model="model.category"
                dictCode="pf_category"
                placeholder="请选择BOM类别"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="BOM类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag type="list" v-model="model.type" dictCode="pf_type" placeholder="请选择BOM类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="版本号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <a-input v-model="model.year" placeholder="请输入版本号"></a-input>
              <!-- <a-date-picker
                ref="datePicker"
                placeholder="请选择"
                v-model="model.year"
                mode="year"
                value-format="YYYY"
                format="YYYY"
                :open="datePickerOpen"
                @panelChange="onDatePickerChange"
                @openChange="onDatePickerOpenChange"
                style="width: 100%"
              /> -->
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <!-- 新增 -->
          <a-col :span="24">
            <a-button type="primary" icon="" size="large" @click="addmaterialFormula"> 新增BOM明细 </a-button>
            <erp-goods-list-model
              ref="selectGoodsList"
              :modalWidth="modalWidth"
              :category="category"
              @goodsOk="goodsOk"
              checkval="checkbox"
            >
            </erp-goods-list-model>
          </a-col>
          <a-col :span="24">
            <!-- 表格 -->
            <a-table
              bordered

              :data-source="model.detailList"
              tableLayout="fixed"
              :columns="materialColumns"
              :rowKey="(record) => record.detailNo"
              :pagination="false"
            >
              <!--              <template slot="formula" slot-scope="text, record">-->
              <!--                <editable-cell :text="text" @change="onCellChange(record.key, 'name', $event)" />-->
              <!--              </template>-->
              <template slot="formula" slot-scope="text, record">
                <editable-cell-2 :text="text" @change="onCellChange(record, 'formula', $event)"></editable-cell-2>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.materialId)">
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
                <!--                <a @click="handleEdit(record)">保存</a>-->
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, postAction, getAction, deleteAction } from '@/api/manage'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import Moment from 'moment'
import EditableCell2 from '@/components/table/EditableCell2.vue'

export default {
  name: 'ErpGoodsFormulaForm',
  components: { ErpGoodsListModel, EditableCell2 },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      datePickerOpen: false,
      model: {
        code: '',
        category: 1,
        detailList: [],
        year: '',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      category: '4',
      modalWidth: 1250,
      materialColumns: [
        {
          title: '编号',
          dataIndex: 'detailNo',
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
        },
        {
          title: '规格',
          dataIndex: 'spec',
        },
        {
          title: '是否客户自带料',
          dataIndex: 'isClientOwn',
        },
        {
          title: 'BOM%',
          dataIndex: 'formula',
          scopedSlots: { customRender: 'formula' },
          width: 150,
        },
        {
          title: '实际数量',
          dataIndex: 'actualQuantity',
        },
        {
          title: '配方公式',
          dataIndex: 'computingFormula',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      validatorRules: {
        code: [{ required: true, message: '请输入BOM编码!' }],
        no: [{ required: true, message: '请输入BOM号!' }],
        name: [{ required: true, message: '请输入BOM名称!' }],
        category: [{ required: true, message: '请输入BOM类别!' }],
        type: [{ required: true, message: '请输入BOM类型!' }],
        year: [{ required: true, message: '请输入版本号!' }],
      },
      url: {
        add: '/base/erpGoodsFormula/add',
        edit: '/base/erpGoodsFormula/edit',
        queryById: '/base/erpGoodsFormula/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    onCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.detailList]
      const target = dataSource.find((item) => item.detailNo === record.detailNo)
      // console.log(target,key,dataIndex,value)
      if (record) {
        target[dataIndex] = value
        this.model.detailList = dataSource
        postAction('/base/erpGoodsFormulaDetail/compute/formula', { list: this.model.detailList, detail: record }).then(
          (res) => {
            if (res.success) {
              this.$set(record, 'actualQuantity', res.result)
              console.log('计算完的值', this.model.detailList)
            }
          }
        )
      }
    },
    onDelete(key) {
      console.log(key)
      const dataSource = [...this.model.detailList]
      this.model.detailList = dataSource.filter((item) => item.materialId != key)
      // deleteAction('base/erpGoodsFormulaDetail/delete',{id:key}).then(res=>{
      //   if(res.success){
      //
      //   }
      // })
    },
    goodsOk: function (datas) {
      console.log("---------datas----------")
      console.log(datas)
      // this.handleAdd();
      let _this = this
      let ids = datas.map((item) => item.id)
      console.log("---------ids----------")
      console.log(ids)
      postAction('/base/erpGoods/list/ids', { ids: datas }).then((res) => {
        console.log("-----------添加BOM明细---------------")
        console.log(res.result)
        let erpGoodsList = res.result
        erpGoodsList.forEach(function (item, index) {
          
          let detail = {}
          detail.detailNo = item.code
          detail.materialName = item.name
          detail.spec = item.noneSpec
          detail.isClientOwn = item.isPublic
          detail.materialId = item.id
          _this.filtermaterialId(item.id)
          _this.model.detailList.push(detail)
          //BOM公式
          getAction('/base/erpGoodsFormulaGs/query', { materialId: item.id }).then((res) => {
            if (res.result && res.result.length > 0) {
              // _this.model.detailList[_this.model.detailList.length - 1].computingFormula = res.result[0].gs;
              _this.model.detailList[_this.model.detailList.length - 1].gsMaterialId = res.result[0].gsMaterialId
              _this.$set(
                _this.model.detailList[_this.model.detailList.length - 1],
                'computingFormula',
                res.result[0].gs
              )
            }
          })
        })
      })
    },
    filtermaterialId(materialId) {
      if (this.model.detailList && this.model.detailList.length > 0) {
        this.model.detailList = this.model.detailList.filter(function (item) {
          return item.materialId !== materialId
        })
      }
    },
    addmaterialFormula: function () {
      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
      // this.$refs.selectGoodsList.add();
      // this.$refs.selectGoodsList.title = "新增";
      // this.$refs.selectGoodsList.disableSubmit = false;
    },
    onDatePickerOpenChange(status) {
      console.log('dalkia')
      this.datePickerOpen = true
    },
    onDatePickerChange: function (dateText) {
      this.datePickerOpen = false
      let date = dateText._d
      console.log('riqi', Moment(date).format('YYYY'))
      this.model.year = date && Moment(date).locale('en').format('YYYY')
    },
    getFormulaCode() {
      postAction('/sys/fillRule/executeRuleByCode/formular_code', {}).then((res) => {
        this.model.code = res.result
      })
    },
    add() {
      this.edit(this.modelDefault)
      //this.getFormulaCode();
    },
    editAfter() {
      if (this.model.id) {
        return;
      }
      this.getFormulaCode()
    },
    edit(record) {
      this.model = Object.assign({}, record)
      if (this.model.id)
        getAction('/base/erpGoodsFormulaDetail/list', { formulaCode: this.model.id }).then((res) => {
          this.model.detailList = res.result
        })
      this.visible = true
      console.log('edit')
      if (typeof this.editAfter === 'function') {
        this.editAfter()
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>
